package edu.scau.ojforwarder.util;

import edu.scau.ojforwarder.bean.BaseResult;
import edu.scau.ojforwarder.bean.NowcoderError;
import edu.scau.ojforwarder.bean.NowcoderStatus;
import edu.scau.ojforwarder.service.NowcoderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;

@Component
public class NowcoderStatusTask extends Thread {

    private final LinkedBlockingQueue<String> submissionIdQueue = new LinkedBlockingQueue<>();
    private final ConcurrentHashMap<String, String> submissionCallbackMap = new ConcurrentHashMap<>();

    @Autowired
    private NowcoderService nowcoderService;

    private Logger logger = LoggerFactory.getLogger(NowcoderStatusTask.class);

    public NowcoderStatusTask() {
        start();
    }

    @Override
    public void run() {
        while (true) {
            try {
                String submissionId = submissionIdQueue.take();
                BaseResult<NowcoderStatus> status = nowcoderService.getStatus(submissionId);
                if (status.getCode() == NowcoderError.SUCCESS.getCode() && (
                        status.getData().getStatus().equals(NowcoderStatus.PENDING) ||
                        status.getData().getStatus().equals(NowcoderStatus.QUEUING)))
                    submissionIdQueue.put(submissionId);
                else {
                    CallbackUtil.sendResult(submissionCallbackMap.get(submissionId), status);
                    submissionCallbackMap.remove(submissionId);
                }
                Thread.sleep(1000);
            } catch (Exception e) {
                logger.error("牛客网获取结果失败。", e);
            }
        }
    }

    public void addSubmission(String submissionId, String callbackUrl) {
        submissionCallbackMap.put(submissionId, callbackUrl);
        try {
            submissionIdQueue.put(submissionId);
        } catch (InterruptedException e) {
            logger.error(e.getMessage(), e);
        }
    }
}
